/**
 * Index Action
 */
var CKL     = require("../utils/checklogin"),
Response    = require("../utils/response"),
DaoMysql    = require('../models/dao-mysql').DaoMysql,
CacheRedis  = require('../models/cache-redis').CacheRedis,
User        = require('../models/user').User;

module.exports = function(app){	
	
	var dao = new DaoMysql(app.envConfig.dbMysql, app.mysqlClient, app.logmessage, new CacheRedis(app.envConfig.storeRedis, app.redisClient, app.logmessage, app.defs.DEFAULT_CACHE_EXPIRE_SECS));
	
	//进入登录页面
	app.get(app.envConfig.routes.index.url, function(req,res){
		var msg=req.flash('info').toString();
		if(!msg){
			msg="请输入用户名和密码";
		}
		Response.render(app,res,app.envConfig.routes.index.page,{info:msg});
	});
	
	//登录操作
	app.post(app.envConfig.routes.index_login.url, function(req, res){
		dao.search(User,"username='"+req.body.uname+"'", function(err,results,total) {
			 if (err || results.length<1) {
				 req.flash('info', '用户不存在'); 
		         return Response.redirect(app,res,app.envConfig.routes.index.url); 
			 }
			 var user=results[0];
			 if(user.password !=req.body.upwd){
		         req.flash('info', '密码错误'); 
		         return Response.redirect(app,res,app.envConfig.routes.index.url); 
		     }
			 if(user.online ==1 ){
		         req.flash('info', '此帐号已经登录'); 
		         return Response.redirect(app,res,app.envConfig.routes.index.url); 
		     }
			 req.session.user = user;
	         req.flash('success','登陆成功');
	         req.flash('info',"");
	         if(req.session.user.role=='0'){
	        	 return Response.redirect(app,res,app.envConfig.routes.index_login.admin); 
	         }else{
	        	 return Response.redirect(app,res,app.envConfig.routes.index_login.service); 
	         }
	    });
	 });
};